<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Social extends CF_Controller {

	public function __construct() {
		parent::__construct();
		$this->load->library('connector');
		$this->load->library('user_login');
		$this->load->library('form_validation');
		$this->load->model('user/users', 'users');
	}

	public function callback()
	{
		$vendor = $this->uri->segment(3);
		$this->connector->init_vendorinfo($vendor);
		$this->connector->get_accesstoken($vendor);
		$userinfo = $this->connector->get_userinfo($vendor);
		$userinfo['vendor'] = $vendor;
		$this->session->set_userdata('social_user_info',$userinfo);
		header('location:'.site_url('social/bind/'.$vendor));
	}

	public function unbind()
	{
		$this->check_login();
		$this->load->model('connector_mdl');
		$vendor = $this->uri->segment(3);
		if(!$vendor){
			redirect('user/login');
		}
		$this->connector_mdl->del_connector_by_vendor_uid($vendor,$this->user_login->get_user_id());
		redirect('user/profile');
	}
	public function bangding()
	{
		$this->load->model('connector_mdl');
		$vendor = $this->uri->segment(3);
		$social_user_info = $this->session->userdata('social_user_info');

		$val = $this->form_validation;
		$val->set_rules('bd_email', 'bd_email', 'trim|required|xss_clean');
		$val->set_rules('bd_passwd', 'bd_passwd', 'trim|required|xss_clean');
		if ($val->run() AND $this->user_login->login($val->set_value('bd_email'), $val->set_value('bd_passwd'), 0))
		{
			$social_connector = $this->connector_mdl->get_bind_by_vendor_and_suid($vendor,$social_user_info['uid']);
			if($social_connector){
				redirect('user/login');//已经被其他帐号绑定
			}else{
				if($this->user_login->get_user_id()){
					//已登录绑定当前帐号
					$connector_data['user_id'] = $this->user_login->get_user_id();
					$connector_data['social_userid'] = $social_user_info['uid'];
					$connector_data['vendor'] = $vendor;
					$connector_data['vendor_info'] = serialize($this->session->userdata('social_'.$vendor.'_info'));
					$connector_data['username'] = $social_user_info['screen_name'];
					$connector_data['name'] = $social_user_info['name'];
					$connector_data['description'] = $social_user_info['description'];
					$connector_data['homepage'] = $social_user_info['url'];
					$connector_data['avatar'] = $social_user_info['avatar'];
					$connector_data['email'] = $social_user_info['email'];
					$connector_data['gender'] = $social_user_info['gender'];
					$connector_data['location'] = $social_user_info['location'];
					$this->connector_mdl->add_connector($connector_data);
					redirect('');
				}else{

					echo "<script>alert('验证不通过');</script>";
				}
			}
		}
		else
		{
			// 被踢用户
			if ($this->user_login->is_banned())
			{
				 
				echo "<script>alert('帐号被禁用');</script>";

			}
			else
			{
				echo "<script>alert('验证不通过');</script>";
				// 如果登录尝试超过最大尝试配置 显示验证码
				if ($this->user_login->is_max_login_attempts_exceeded())
				{
					echo "<script>alert('错误次数过多！请刷新网页');</script>";
				}
			}
		}
		$this->load->view('auth/bangding_user',$social_user_info);
	}
	public function bind()
	{
		$this->load->model('connector_mdl');
		$vendor = $this->uri->segment(3);
		$social_user_info = $this->session->userdata('social_user_info');

		if(!$vendor || $vendor != $social_user_info['vendor']){
			$this->clear_socialinfo($vendor);
			redirect('user/login');
		}

		if($this->input->post()){
			//社会化注册写库并登录
			if($this->validate_bind_form() == TRUE){
				$data['email'] = md5(random_string('alnum', 5)).'@ichufang.cn';
				$data['username'] = $this->input->post('nickname');
				$data['sex'] = $social_user_info['gender'];

				$data['password'] = crypt(pass_encode($this->input->post('password')));
				$data['last_ip'] = $this->input->ip_address();
				//$data['is_active'] = 1;
				//$data['is_social'] = 1;
				if($this->users->create_user($data))
				{ 
					$uid = $this->db->insert_id();
				}

				$connector_data['user_id'] = $uid;
				$connector_data['social_userid'] = $social_user_info['uid'];
				$connector_data['vendor'] = $vendor;
				$connector_data['vendor_info'] = serialize($this->session->userdata('social_'.$vendor.'_info'));
				$connector_data['username'] = $social_user_info['screen_name'];
				$connector_data['name'] = $social_user_info['name'];
				$connector_data['description'] = $social_user_info['description'];
				$connector_data['homepage'] = $social_user_info['url'];
				$connector_data['avatar'] = $social_user_info['avatar'];
				//$connector_data['email'] = $social_user_info['email'];
				$connector_data['gender'] = $social_user_info['gender'];
				$connector_data['location'] = $social_user_info['location'];
				$this->connector_mdl->add_connector($connector_data);

				$this->save_remote_avatar($social_user_info['avatar'], $uid);
				$user = $this->users->get_user_by_id($uid)->row();
				//登录系统
				$this->user_login->_set_session($user);
				$this->user_login->_set_last_ip_and_last_login($user->id);
				//
				$this->clear_socialinfo($vendor);

				redirect('');
			}else{
				$this->load->view('auth/bangding_user',$social_user_info);
			}
		}else{
			$social_connector = $this->connector_mdl->get_bind_by_vendor_and_suid($vendor,$social_user_info['uid']);
			if($social_connector){
				if($this->user_login->get_user_id()&&$social_connector->user_id!=$this->user_login->get_user_id()){
					header("Content-Type:text/html;charset=utf-8");
					show_error("此账号已被其他用户绑定，本操作已取消",500,'该行为被取消');
				}else{
					$local_query = $this->users->get_user_by_id($social_connector->user_id);
					if($local_query->num_rows() == 1){
						//社会化找到用户进行登录操作 
						//更新头像地址
						$update_connect_data['avatar'] = $social_user_info['avatar'];
						//$update_local_data['avatar_remote'] = $social_user_info['avatar'];
						//need update remote avatar
						$this->connector_mdl->edit_connector($social_connector->connect_id,$update_connect_data);
						//$this->user_model->edit_user($social_connector->user_id,$update_local_data);
						//
						$local_user = $this->users->get_user_by_id($social_connector->user_id)->row();
						//登录系统
						$this->user_login->_set_session($local_user);
						$this->user_login->_set_last_ip_and_last_login($local_user->id);
						//
						$this->clear_socialinfo($vendor);
						redirect('');
					}else{
						//没找到用户数据 删除社会化登录库
						$this->connector_mdl->del_connector_by_vendor_uid($vendor, $social_connector->user_id);
						redirect('');
					}
				}
			}else{
				if($this->user_login->get_user_id()){
					//已登录绑定当前帐号
					$connector_data['user_id'] = $this->user_login->get_user_id();
					$connector_data['social_userid'] = $social_user_info['uid'];
					$connector_data['vendor'] = $vendor;
					$connector_data['vendor_info'] = serialize($this->session->userdata('social_'.$vendor.'_info'));
					$connector_data['username'] = $social_user_info['screen_name'];
					$connector_data['name'] = $social_user_info['name'];
					$connector_data['description'] = $social_user_info['description'];
					$connector_data['homepage'] = $social_user_info['url'];
					$connector_data['avatar'] = $social_user_info['avatar'];
					$connector_data['email'] = $social_user_info['email'];
					$connector_data['gender'] = $social_user_info['gender'];
					$connector_data['location'] = $social_user_info['location'];
					$this->connector_mdl->add_connector($connector_data);
					redirect('user/profile');
				}else{

					$this->load->view('auth/bangding_user',$social_user_info);
				}
			}
		}
	}

	private function save_remote_avatar($url,$uid)
	{
		/*if(function_exists('curl_init')){
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL,$url);
			curl_setopt($ch, CURLOPT_TIMEOUT, 5);
			curl_setopt($ch, CURLOPT_USERAGENT, _USERAGENT_);
			curl_setopt($ch, CURLOPT_REFERER,_REFERER_);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			$content = curl_exec($ch);
			curl_close($ch);
		}else{
			$content = @file_get_contents($url);
		}

		$avatar_info = $this->user_model->get_avatarinfo($uid);
		$avatar_dir = FCPATH.$avatar_info['dir'];
		(!is_dir($avatar_dir))&&@mkdir($avatar_dir,0777,true);

		file_exists($avatar_dir.$avatar_info['orgin']) && unlink($avatar_dir.$avatar_info['orgin']);
		file_exists($avatar_dir.$avatar_info['large']) && unlink($avatar_dir.$avatar_info['large']);
		file_exists($avatar_dir.$avatar_info['middle']) && unlink($avatar_dir.$avatar_info['middle']);
		file_exists($avatar_dir.$avatar_info['small']) && unlink($avatar_dir.$avatar_info['small']);
		
		$file_path = $avatar_dir.$avatar_info['orgin'];
		if(!empty($content) && @file_put_contents($file_path,$content) > 0)
		{
			$this->load->library('tupu_image_lib');
			$this->tupu_image_lib->create_thumb($file_path, 'large', 150,150);
			$this->tupu_image_lib->create_thumb($file_path, 'middle', 50,50);
			$this->tupu_image_lib->create_thumb($file_path, 'small', 16,16);
			//update local avatar
			$user_update['avatar_local'] = $avatar_info['dir'].$avatar_info['filename'];
			return $this->user_model->edit_user($uid,$user_update);
		}else{
			$user_update['avatar_local'] = $this->user_model->create_default_avatar($uid);
			return $this->user_model->edit_user($uid,$user_update);
		}
		return false;*/
		//$this -> load -> model('user_model');
		//$this -> user_model -> create_default_avatar($uid);
		return true;
	}

	private function clear_socialinfo($vendor){
		$this->session->unset_userdata(
		array(
				'social_api_info'=>'',
				'social_user_info'=>'',
				'social_'.$vendor.'_info'=>''
				));
	}

	private function validate_bind_form($name = ''){
		$this->form_validation->set_rules('nickname', '昵称' , 'trim|required|min_length[2]|max_length[20]|callback_check_nickname|xss_clean');
		if ($this->form_validation->run() == FALSE){
			return FALSE;
		}else{
			return TRUE;
		}
	}

	function check_nickname($nickname){
		$users = $this->user_login->is_username_available($nickname);

		if(!$users){
			$this->form_validation->set_message('check_nickname', '用户名已经存在！'.$users);
			return FALSE;
		}else{
			return TRUE;
		}
	}
}